/**
 * API客户端配置
 */

const API_BASE_URL = 'http://localhost:8000/api/v1';

// API响应类型
export interface ApiResponse<T> {
  data: T;
  message?: string;
  success: boolean;
}

// 用户相关类型
export interface User {
  id: number;
  username: string;
  email: string;
  full_name: string;
  avatar?: string;
  phone?: string;
  department?: string;
  position?: string;
  is_active: boolean;
  created_at: string;
  updated_at?: string;
  last_login?: string;
}

// 聊天相关类型
export interface ChatSession {
  id: number;
  session_id: string;
  dify_conversation_id?: string;
  user_id: number;
  title: string;
  status: string;
  message_count: number;
  total_tokens?: number;
  satisfaction_score?: number;
  meta_data?: any;
  tags?: string[];
  created_at: string;
  updated_at: string;
  last_message_at?: string;
}

export interface ChatMessage {
  id: number;
  message_id: string;
  session_id: number;
  role: 'user' | 'assistant';
  content: string;
  content_type?: string;
  model?: string;
  tokens?: number;
  response_time?: number;
  rating?: number;
  feedback?: string;
  meta_data?: any;
  created_at: string;
}

// 消息任务状态
export interface MessageTaskStatus {
  task_id: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  progress?: number;
  message?: ChatMessage;
  error?: string;
  created_at: string;
  updated_at: string;
}

// 发布相关类型
export interface Release {
  id: number;
  version: string;
  title: string;
  description: string;
  status: 'pending' | 'in_progress' | 'completed' | 'failed';
  environment: 'development' | 'staging' | 'production';
  created_by: number;
  created_at: string;
  scheduled_at?: string;
  meta_data?: any;
}

// 分析相关类型
export interface UserBehavior {
  id: number;
  user_id: number;
  action: string;
  module: string;
  resource?: string;
  created_at: string;
  meta_data?: any;
}

export interface PageView {
  id: number;
  user_id?: number;
  page_url: string;
  page_title?: string;
  created_at: string;
}

// API客户端类
class ApiClient {
  private baseURL: string;
  private token: string | null = null;
  private refreshToken: string | null = null;
  private isRefreshing: boolean = false;
  private failedQueue: Array<{ resolve: Function; reject: Function }> = [];

  constructor(baseURL: string) {
    this.baseURL = baseURL;
    this.token = localStorage.getItem('access_token');
    this.refreshToken = localStorage.getItem('refresh_token');
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {},
    isRetry: boolean = false
  ): Promise<T> {
    const url = `${this.baseURL}${endpoint}`;
    const config = {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
        ...(this.token ? { Authorization: `Bearer ${this.token}` } : {})
      }
    };

    try {
      // 使用 AbortController 实现超时控制
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 600000); // 10分钟超时
      
      const response = await fetch(url, {
        ...config,
        signal: controller.signal
      });
      
      // 清除超时计时器
      clearTimeout(timeoutId);

      // 处理401错误 - token过期
      if (response.status === 401 && !isRetry && endpoint !== '/auth/login' && endpoint !== '/auth/refresh') {
        return this.handleTokenExpired(endpoint, options);
      }

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`API请求失败: ${response.status} ${response.statusText}`, errorText);
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
      }

      return response.json();
    } catch (error) {
      if (error instanceof DOMException && error.name === 'AbortError') {
        throw new Error('请求超时，请稍后重试');
      }
      console.error('API请求异常:', error);
      throw error;
    }
  }

  // 处理token过期
  private async handleTokenExpired<T>(endpoint: string, options: RequestInit): Promise<T> {
    if (this.isRefreshing) {
      // 如果正在刷新token，将请求加入队列
      return new Promise((resolve, reject) => {
        this.failedQueue.push({ resolve, reject });
      }).then(() => {
        return this.request<T>(endpoint, options, true);
      });
    }

    this.isRefreshing = true;

    try {
      await this.refreshAccessToken();
      // 处理队列中的请求
      this.processQueue(null);
      // 重试原始请求
      return this.request<T>(endpoint, options, true);
    } catch (error) {
      // 刷新失败，清空队列并重定向到登录页
      this.processQueue(error);
      this.handleAuthFailure();
      throw error;
    } finally {
      this.isRefreshing = false;
    }
  }

  // 刷新访问token
  private async refreshAccessToken(): Promise<void> {
    if (!this.refreshToken) {
      throw new Error('没有refresh token');
    }

    try {
      const response = await fetch(`${this.baseURL}/auth/refresh`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.refreshToken}`
        }
      });

      if (!response.ok) {
        throw new Error('刷新token失败');
      }

      const data = await response.json();
      this.token = data.access_token;
      localStorage.setItem('access_token', data.access_token);
      
      if (data.refresh_token) {
        this.refreshToken = data.refresh_token;
        localStorage.setItem('refresh_token', data.refresh_token);
      }
    } catch (error) {
      console.error('刷新token失败:', error);
      throw error;
    }
  }

  // 处理队列中的请求
  private processQueue(error: any): void {
    this.failedQueue.forEach(({ resolve, reject }) => {
      if (error) {
        reject(error);
      } else {
        resolve();
      }
    });
    
    this.failedQueue = [];
  }

  // 处理认证失败
  private handleAuthFailure(): void {
    this.token = null;
    this.refreshToken = null;
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('token_type');
    localStorage.removeItem('user_info');
    
    // 触发全局token过期处理器
     try {
       triggerGlobalTokenExpiry();
     } catch (error) {
       // 兜底方案：触发自定义事件，通知应用需要重新登录
       window.dispatchEvent(new CustomEvent('auth:expired'));
       // 如果全局处理器不可用，跳转到登录页面
       window.location.href = '/login';
     }
  }

  // 认证相关
  async login(username: string, password: string) {
    // 确保使用完整的API路径
    const response = await this.request<{ access_token: string; refresh_token: string; token_type: string; user_info: any }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    });
    
    this.token = response.access_token;
    this.refreshToken = response.refresh_token;
    localStorage.setItem('access_token', response.access_token);
    localStorage.setItem('refresh_token', response.refresh_token);
    localStorage.setItem('token_type', response.token_type);
    
    // 如果有用户信息，也保存起来
    if (response.user_info) {
      localStorage.setItem('user_info', JSON.stringify(response.user_info));
    }
    
    return response;
  }

  async logout() {
    this.token = null;
    this.refreshToken = null;
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('token_type');
    localStorage.removeItem('user_info');
    return this.request<void>('/auth/logout', { method: 'POST' });
  }

  async getCurrentUser(): Promise<User> {
    return this.request<User>('/auth/me');
  }

  // 用户管理
  async getUsers(): Promise<User[]> {
    return this.request<User[]>('/users/');
  }

  async getUser(id: number): Promise<User> {
    return this.request<User>(`/users/${id}`);
  }

  // 聊天管理
  async getChatSessions(): Promise<ChatSession[]> {
    return this.request<ChatSession[]>('/chat/sessions');
  }

  async getChatMessages(sessionId: string): Promise<ChatMessage[]> {
    return this.request<ChatMessage[]>(`/chat/sessions/${sessionId}/messages`);
  }

  async createChatSession(title: string): Promise<ChatSession> {
    return this.request<ChatSession>('/chat/sessions', {
      method: 'POST',
      body: JSON.stringify({ title }),
    });
  }

  async deleteChatSession(sessionId: string): Promise<void> {
    return this.request<void>(`/chat/sessions/${sessionId}`, {
      method: 'DELETE',
    });
  }

  // 发送消息 - 异步版本，返回任务状态
  async sendMessage(sessionId: string, content: string): Promise<MessageTaskStatus> {
    try {
      return await this.request<MessageTaskStatus>(`/chat/sessions/${sessionId}/messages`, {
        method: 'POST',
        body: JSON.stringify({ content }),
      });
    } catch (error) {
      console.error('发送消息失败:', error);
      throw new Error(`发送消息失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  // 获取任务状态
  async getTaskStatus(taskId: string): Promise<MessageTaskStatus> {
    try {
      return await this.request<MessageTaskStatus>(`/chat/tasks/${taskId}`);
    } catch (error) {
      console.error('获取任务状态失败:', error);
      throw new Error(`获取任务状态失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  // 发布管理
  async getReleases(): Promise<Release[]> {
    return this.request<Release[]>('/release/releases');
  }

  async getRelease(id: string): Promise<Release> {
    return this.request<Release>(`/release/releases/${id}`);
  }

  async createRelease(data: Partial<Release>): Promise<Release> {
    return this.request<Release>('/release/releases', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // 数据分析
  async getUserBehaviors(): Promise<UserBehavior[]> {
    return this.request<UserBehavior[]>('/analytics/behaviors');
  }

  async getPageViews(): Promise<PageView[]> {
    return this.request<PageView[]>('/analytics/pageviews');
  }

  async trackUserBehavior(data: Partial<UserBehavior>): Promise<void> {
    return this.request<void>('/analytics/track/behavior', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async trackPageView(data: Partial<PageView>): Promise<void> {
    return this.request<void>('/analytics/track/pageview', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async getDashboardStats(): Promise<any> {
    return this.request<any>('/dashboard/overview');
  }
}

// 导出API客户端实例
export const apiClient = new ApiClient(API_BASE_URL);

// 导出便捷方法
export const api = {
  // 认证
  login: (username: string, password: string) => apiClient.login(username, password),
  logout: () => apiClient.logout(),
  getCurrentUser: () => apiClient.getCurrentUser(),

  // 用户
  getUsers: () => apiClient.getUsers(),
  getUser: (id: number) => apiClient.getUser(id),

  // 聊天
  getChatSessions: () => apiClient.getChatSessions(),
  getChatMessages: (sessionId: string) => apiClient.getChatMessages(sessionId),
  createChatSession: (title: string) => apiClient.createChatSession(title),
  deleteChatSession: (sessionId: string) => apiClient.deleteChatSession(sessionId),
  sendMessage: (sessionId: string, content: string) => apiClient.sendMessage(sessionId, content),
  getTaskStatus: (taskId: string) => apiClient.getTaskStatus(taskId),

  // 发布
  getReleases: () => apiClient.getReleases(),
  getRelease: (id: string) => apiClient.getRelease(id),
  createRelease: (data: Partial<Release>) => apiClient.createRelease(data),

  // 分析
  getUserBehaviors: () => apiClient.getUserBehaviors(),
  getPageViews: () => apiClient.getPageViews(),
  trackUserBehavior: (data: Partial<UserBehavior>) => apiClient.trackUserBehavior(data),
  trackPageView: (data: Partial<PageView>) => apiClient.trackPageView(data),
  getDashboardStats: () => apiClient.getDashboardStats(),
};